package com.test.test11.task;

import android.os.AsyncTask;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.test.test11.SharedConstants;
import com.test.test11.WebURL;
import com.test.test11.entity.ResponseResult;
import com.test.test11.entity.UserDeviceRelationship;
import com.test.test11.http.AfterRequest;
import com.test.test11.http.HttpClient;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 设备删除
 */

public class DeviceDeleteTask extends AsyncTask<UserDeviceRelationship,Void, ResponseResult>{

    private static final String TAG = "DEVICE_DELETE_TASK";

    private AfterRequest afterRequest;

    public DeviceDeleteTask(AfterRequest afterRequest){
        this.afterRequest = afterRequest;
    }

    /**
     * 后台获取进程
     * @param userDeviceRelationships 只有一个参数，关系id不能为空
     * @return
     */
    @Override
    protected ResponseResult doInBackground(UserDeviceRelationship... userDeviceRelationships) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", userDeviceRelationships[0].getId());
        try {
            String res = HttpClient.getInstance().post(WebURL.DEVICE_DELETE_URL, params);
            if(StringUtils.isBlank(res)){
                return null;
            }
            ObjectMapper mapper = new ObjectMapper();
            ResponseResult result = mapper.readValue(res, ResponseResult.class);
            if(result.getCode()==0){
                // 删除成功的话从本地删除设备信息
                SharedConstants.deleteDevice(userDeviceRelationships[0]);
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * UI线程中应该执行的操作，此处已经将设备列表信息填充到程序中了
     * @param s
     */
    @Override
    protected void onPostExecute(ResponseResult s) {
        if(s==null){
            afterRequest.failure(-1, "请检查网络连接");
        }else if(s.getCode()==0){
            afterRequest.success();
        }else{
            afterRequest.failure(s.getCode(), s.getMsg());
        }
    }
}
